/*
 * ==========================================================================*\
 * | $Id: Initializer.java 360 2011-02-20 19:43:41Z vtwoods@gmail.com $
 * |*-------------------------------------------------------------------------*|
 * | Copyright (C) 2009 Virginia Tech | | This file is part of CloudSpace. | |
 * CloudSpace is free software; you can redistribute it and/or modify | it under
 * the terms of the GNU General Public License as published | by the Free
 * Software Foundation; either version 3 of the License, or | (at your option)
 * any later version. | | CloudSpace is distributed in the hope that it will be
 * useful, | but WITHOUT ANY WARRANTY; without even the implied warranty of |
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | GNU General
 * Public License for more details. | | You should have received a copy of the
 * GNU General Public License | along with CloudSpace; if not, see
 * <http://www.gnu.org/licenses/>.
 * \*==========================================================================
 */

package student.web.internal;

import java.util.Map;

import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Desktop;
import org.zkoss.zk.ui.Page;
import org.zkoss.zk.ui.util.EventInterceptor;
import org.zkoss.zkplus.databind.AnnotateDataBinderInit;

import cloudspace.stats.StatEvent;
import cloudspace.stats.StatisticsService;
import cloudspace.vm.VM;


// -------------------------------------------------------------------------
/**
 * Initialize a ZK page for student use.
 * 
 * @author Stephen Edwards
 * @author Last changed by $Author: vtwoods@gmail.com $
 * @version $Revision: 360 $, $Date: 2011-02-09 23:08:05 -0500 (Wed, 09 Feb
 *          2011) $
 */
public class Initializer extends AnnotateDataBinderInit
{
    public static boolean debug = false;

    private String _compPath = null;


    // ----------------------------------------------------------
    /**
     * Initialize the page, which forces the bean shell Java interpreter to be
     * loaded for this page, a step that is necessary to set up class loading
     * for Java classes stored in the page's directory.
     * 
     * @param page
     *            the page to initialize
     * @param args
     *            any arguments that are provided are ignored
     */
    @Override
    public void doInit( Page page, @SuppressWarnings("rawtypes") Map args )
    {
        // VM currentVM = VM.currentVM();
        /*
         * if (currentVM != null) {
         * currentVM.removeDesktop(Executions.getCurrent
         * ().getDesktop().getId()); }
         */
        if ( args.containsKey( "arg0" ) )
        {
            if ( args.get( "arg0" ) instanceof String )
                _compPath = (String)args.get( "arg0" );
        }
        VM newVM = VM.lookupVM();
        newVM.enter();
        // VM.currentVM().addDesktop(Executions.getCurrent().getDesktop().getId());

        super.doInit( page, args );

        // System.out.println( getClass().getName() + ": init( "
        // + page.getRequestPath()
        // + ")");

        // Force the Java interpreter to initialize for this page
        page.getInterpreter( "java" );
    }


    // ----------------------------------------------------------
    /**
     * After the data binder has done its work, install a piggyback event
     * handler to auto-update bindings.
     * 
     * @param page
     *            the page that was just composed
     * @param comps
     * @throws Exception
     */
    @Override
    public void doAfterCompose( Page page, Component[] comps ) throws Exception
    {
        if ( debug )
        {
            System.out.println( "Entering doAfterCompose: " + page );
        }
        if ( this._compPath == null
            || !( _compPath.startsWith( "./" ) || _compPath.startsWith( "../" ) ) )
        {
            if ( page.getAttribute( "binder" ) != null )
            {
                // There is already a binder on this page, so skip
                // initialization
                return;
            }
        }
        StatisticsService.getStatService()
            .observe( new StatEvent( "PagesLoaded" ) );
        super.doAfterCompose( page, comps );
        if ( page.getDesktop().getAttribute( "interceptor" ) == null )
        {
            Desktop desktop = page.getDesktop();
            EventInterceptor interceptor = new BindingUpdater( desktop );
            desktop.addListener( interceptor );
            desktop.setAttribute( "interceptor", interceptor );
        }

        if ( debug )
        {
            System.out.println( "doAfterCompose called: " + page );
        }

        // EventListener listener = new EventListener() {
        // public void onEvent(Event event)
        // {
        // _binder.loadAll();
        // }
        // };
        // System.out.println("Adding listeners ...");
        // for(Iterator it = page.getRoots().iterator(); it.hasNext();)
        // {
        // addButtonListener((Component) it.next(), listener);
        // }
    }

    // ----------------------------------------------------------
    // private void addButtonListener(Component c, EventListener listener)
    // {
    // System.out.println("  inspecting: " + c);
    // System.out.println("    has onClick ="
    // + Events.isListened(c, Events.ON_CLICK, false));
    // if (c instanceof Button
    // || c instanceof Toolbarbutton)
    // {
    // c.addEventListener(Events.ON_CLICK, listener);
    // c.addEventListener(Events.ON_DOUBLE_CLICK, listener);
    // c.addEventListener(Events.ON_RIGHT_CLICK, listener);
    // }
    // // else if (c instanceof Listbox)
    // // {
    // // c.addEventListener(Events.ON_SELECT, listener);
    // // }
    // // else if (c instanceof A)
    // // {
    // // c.addEventListener(Events.ON_CLICK, listener);
    // // }
    // for(Iterator it = c.getChildren().iterator(); it.hasNext();)
    // {
    // addButtonListener((Component) it.next(), listener); //recursive
    // }
    // }
}
